package la.bbs558.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import la.bbs558.dao.BbsSectionDao;
import la.bbs558.entity.BbsBoard;
import la.bbs558.entity.BbsSection;
import la.bbs558.entity.params.SectionSearchPage;
import la.bbs558.entity.params.SectionUpdateParams;
import la.bbs558.satoken.StpAdminUtil;
import la.bbs558.service.BbsBoardService;
import la.bbs558.service.BbsSectionService;
import la.bbs558.util.Objs;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Shanks
 * @date: 2023/12/15 22:43
 * @desc:
 */
@Service
@RequiredArgsConstructor
public class BbsSectionServiceImpl extends ServiceImpl<BbsSectionDao, BbsSection> implements BbsSectionService {

    private final BbsSectionDao bbsSectionDao;

    @Resource
    private BbsBoardService bbsBoardService;

    @Override
    public void addSectionForAdmin(SectionUpdateParams updateParams) {
        BbsSection bbsSection = new BbsSection()
                .setSectionName(updateParams.getSectionName())
                .setSort(999)
                .setCreateUser(StpAdminUtil.getLoginIdAsLong());
        bbsSectionDao.insert(bbsSection);
        updateBoardSectionId(updateParams.getBoardIdList(), bbsSection.getId());
    }

    @Override
    public void updateSectionForAdmin(SectionUpdateParams updateParams) {
        Objs.isTrue(updateParams.getId() != null, "分区ID不能为空");
        BbsSection bbsSection = new BbsSection()
                .setId(updateParams.getId())
                .setSectionName(updateParams.getSectionName())
                .setSort(updateParams.getSort());
        bbsSectionDao.updateById(bbsSection);
        updateBoardSectionId(updateParams.getBoardIdList(), bbsSection.getId());
    }

    @Override
    public void listSectionByPageForAdmin(SectionSearchPage searchPage) {
        bbsSectionDao.selectListSectionByPageForAdmin(searchPage);
    }

    @Override
    public void removeSectionByIdForAdmin(Long id) {
        bbsSectionDao.deleteById(id);
        bbsBoardService.lambdaUpdate()
                .set(BbsBoard::getSectionId, null)
                .eq(BbsBoard::getSectionId, id)
                .update();
    }

    private void updateBoardSectionId(List<Long> boardIdList, Long sectionId) {
        if (boardIdList == null || boardIdList.isEmpty()) {
            return;
        }
        BbsBoard bbsBoard = new BbsBoard().setSectionId(sectionId);
        boardIdList.forEach(boardId -> {
            bbsBoard.setId(boardId);
            bbsBoardService.updateById(bbsBoard);
        });
    }
}
